#include <Channel.h>
#include <EventLoop.h>
#include <unistd.h>

Channel::Channel(EventLoop *lp, int fd, bool usePool):_loop(lp), _fd(fd), _events(0), _revents(0), _inPoll(false), _usePool(usePool)
{
}

Channel::~Channel()
{
    if (_fd != -1) {
        close(_fd);
        _fd = -1;
    }
}

void Channel::enableReading() {
    _events |= EPOLLIN | EPOLLPRI;
    // epoll更新
    _loop->updateChannel(this);
}

void Channel::useET() {
    _events |= EPOLLET;
    _loop->updateChannel(this);
}

void Channel::setRevents(uint32_t ev) {
    _revents = ev;
}

uint32_t Channel::getRevents() {
    return _revents;
}

void Channel::setInPoll() {
    _inPoll = true;
}

bool Channel::isInPoll() {
    return _inPoll;
}

int Channel::getFd() {
    return _fd;
}

uint32_t Channel::getEvents() {
    return _events;
}

void Channel::setReadCallback(std::function<void()> callback) {
    _readCallback = callback;
}

void Channel::setWriteCallback(std::function<void()> callback) {
    _writeCallback = callback;
}

void Channel::handleEvent() {
    if (_revents & (EPOLLIN | EPOLLPRI)) {
        if (_usePool) {
            _loop->addThread(_readCallback);
        }else {
            _readCallback();
        }
    }
    if (_revents & (EPOLLOUT)) {
        if (_usePool) {
            _loop->addThread(_writeCallback);
        }else {
            _writeCallback();
        }
    }
}
